namespace Todos.Application.TodoItems.Commands;

[AuthConfig(typeof(TodoItem), ResourceAccessType.RoleLimit, "Create")]
public class AddTodoItemCommand : IRequest<ApiResult>, ICommand
{
    public long ListId { get; set; }

    public TodoItemInDto[] Dtos { get; set; } = [];
}

public class AddTodoItemCommandHandler(IRepository<TodoList> repository) : IRequestHandler<AddTodoItemCommand, ApiResult>
{
    public async Task<ApiResult> Handle(AddTodoItemCommand request, CancellationToken cancellationToken)
    {
        var spec = new TodoListByIdSpec(request.ListId);
        var list = await repository.GetAsync(spec, cancellationToken);
        if (list == null)
        {
            return new ApiResult(ApiResultType.Error, "待办列表不存在");
        }

        foreach (var dto in request.Dtos)
        {
            list.AddItem(dto.Title, dto.Description);
        }
        await repository.UpdateAsync(list, cancellationToken);
        return new ApiResult(ApiResultType.Success, $"{request.Dtos.Length }个待办项创建成功");
    }
}

public class AddTodoItemCommandValidator : AbstractValidator<AddTodoItemCommand>
{
    public AddTodoItemCommandValidator()
    {
        RuleFor(m => m.ListId).NotEmpty().WithMessage("待办列表Id不能为空");
        RuleForEach(m => m.Dtos).ChildRules(dto =>
        {
            dto.RuleFor(m => m.Title).NotEmpty().WithMessage("待办项标题不能为空")
                .MaximumLength(255).WithMessage("待办项标题长度不能超过255个字符");
            dto.RuleFor(m => m.Description).MaximumLength(1000).WithMessage("待办项描述长度不能超过1000个字符");
        });
    }
}
